<script setup lang="ts">
import { watch } from 'vue';
import { QUERY_ASSET_LIST } from '/@/api/modules/equipment/asset-manage';
import { ZCSC_QUERY_ASSET_CODE_BY_QR_CODE } from '/@/api/modules/flow-path/zcsc-asset';
import { state } from './state';
import { Scan2 as AppNutIconScan2 } from '@nutui/icons-vue-taro';
import { scan } from '/@/utils/scan';
import { navigateTo, showLoading } from '@tarojs/taro';
interface Props {
  modelValue: boolean;
  /**
   * 标题
   */
  title?: string;
  /**
   * 请求参数
   */
  options?: AssetManageApi.QueryAssetListReq;
}
const props = withDefaults(defineProps<Props>(), {
  modelValue: false,
  title: '资产',
  options: () => {
    return {};
  },
});

interface Emits {
  (e: 'update:modelValue'): void;
  (e: 'onSelected', info: AssetInfo.Dto): void;
}
const emits = defineEmits<Emits>();

/**
 * @description 列表查询
 * @param page -当前页
 * @param pageSize -每页条数
 * @param keyword
 */
function queryList(page: number = 1, pageSize: number = 15, keyword: string = '') {
  if (!page && state.finished) return;
  state.loading = true;
  showLoading();
  QUERY_ASSET_LIST({
    comQuery: { page, pageSize },
    keyword,
    ...props.options,
  })
    .then((res) => {
      state.loading = false;

      if (
        state.activePage >=
        (res.comQuery?.pageCount ||
          (res.comQuery?.totalCount as number) / (res.comQuery?.pageSize as number) ||
          1)
      )
        state.finished = true;
      if (!res.assetInfoList || !res.assetInfoList.length) return;

      res.assetInfoList.forEach((item) => state.list.push(item));

      state.activePage += 1;
    })
    .catch(() => {
      state.loading = false;
    });
}

/**
 * @function 加载
 */
function onLoading() {
  if (state.finished) return;

  queryList(state.activePage, 15, state.keyword);
}

watch(props, (newProps) => {
  if (!newProps.modelValue) return;
  refresh();
});

/**
 * 每次重新进入
 */
function refresh() {
  state.activePage = 1;
  state.finished = false;
  state.loading = false;
  state.keyword = '';
  state.list = [];
  onLoading();
}

/**
 * 输入关键字刷新列表
 */
function refreshForSearch() {
  state.activePage = 1;
  state.finished = false;
  state.loading = false;
  state.list = [];
  onLoading();
}

function assetScan() {
  scan().then((result) => {
    scanResult(result);
  });
}

/**
 * 扫描结果处理
 */
function scanResult(result: string) {
  console.log('scanMenu ===> scanResult ===>' + result);
  const url = new URL(result);
  let gs1;
  //普通url
  if (url.search) {
    gs1 = url.searchParams.get('gs1');
  } else {
    //hash的url
    const queryString = url.hash.split('?')[1];
    const params = new URLSearchParams(queryString);
    gs1 = params.get('gs1');
  }
  console.log('gs1 ===>', gs1);
  if (!gs1) {
    navigateTo({
      url: '/pages/scan/scan-fail/index?error=unknown',
    });
    return;
  }

  handleByGS1(gs1);
}
/**
 * 需要根据gs1号码，调用资产云接口，获取资产编码
 * @param gs1
 */
function handleByGS1(gs1: string) {
  showLoading();
  ZCSC_QUERY_ASSET_CODE_BY_QR_CODE({ gs1code: gs1 }).then((res) => {
    state.keyword = res.zichanbh || '';
    refreshForSearch();
  });
}
</script>

<template>
  <teleport to="body">
    <nut-popup
      :visible="props.modelValue"
      position="bottom"
      closeable
      round
      :style="{ height: '90vh' }"
      @click-close-icon="emits('update:modelValue')"
      @click-overlay="emits('update:modelValue')"
    >
      <view class="app-asset-list-popup app-popup--2">
        <view class="app-asset-list-popup__header app-popup__header">{{ props.title }}</view>
        <nut-searchbar
          v-model="state.keyword"
          placeholder="请输入设备编号/设备名称"
          @change="refreshForSearch()"
        >
          <template v-slot:rightout>
            <app-nut-icon-scan2 @click="assetScan()" />
          </template>
        </nut-searchbar>
        <scroll-view
          class="app-popup__wrapper"
          :scroll-y="true"
          :lower-threshold="100"
          @scrolltolower="onLoading()"
        >
          <view class="app-asset-list-popup__wrapper">
            <app-asset-item
              v-for="item in state.list"
              :key="item.id"
              :info="item"
              @click="
                () => {
                  emits('onSelected', item);
                }
              "
            />
          </view>

          <view class="app-popup__list-tips">
            <text v-if="!state.list.length">暂无数据！</text>
            <text v-else-if="state.list.length && state.loading">加载中...</text>
            <text v-else-if="state.list.length && state.finished">加载完成!</text>
          </view>
        </scroll-view>
      </view>
    </nut-popup>
  </teleport>
</template>

<style lang="scss">
.app-asset-list-popup {
  &__header {
    font-size: 30px;
    font-weight: bold;
  }
  &__wrapper {
    padding: 20px 20px;
  }
}
</style>
